<template>
  <Dialog width="50%" v-model="dialogVisible" :title="dialogTitle">
    <div class="title">
      <el-form
        :inline="true"
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        label-width="80px"
      >
        <el-form-item label="仓库名称:">
          <span>{{ formData.projectName }}</span>
        </el-form-item>
        <el-form-item label="状态:">
          <span>{{ formData.status }}</span>
        </el-form-item>
        <el-form-item label="详细信息:" v-show="formType === 'StaticTest'">
          <el-link type="primary" @click="toHongjian(paramsData, true)"
            >点击跳转至静态检查详情页面</el-link
          >
        </el-form-item>
      </el-form>
    </div>
    <el-scrollbar height="500px">
      <p v-html="log"></p>
    </el-scrollbar>
  </Dialog>
</template>
<script lang="ts" setup>
import * as CiApi from '@/api/system/ci'
import { setHJToken } from '@/utils/auth'
defineOptions({ name: 'CiForm' })
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = reactive({
  projectName: '',
  status: ''
})
const dialogTitle = ref('') // 弹窗的标题
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const log = ref('')
let paramsData = reactive({})

/** 打开弹窗 */
const open = async (type: string, row: any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  paramsData = row
  formType.value = type
  formData.projectName = row.projectName
  switch (type) {
    case 'StaticTest':
      formData.status = handleStatus(row.scStatus)
      break
    case 'UnitTest':
      formData.status = handleStatus(row.unitTest)
      break
    case 'DeployStatus':
      formData.status = handleStatus(row.deployStatus)
      break
  }
  getLog(type, row)
}

//获取日志
const getLog = async (type, row) => {
  log.value = ''
  const data = await CiApi.getJobLog(row.uuid, type)
  log.value = data.replace(/\n/g, '<br>')
}

//处理状态
const handleStatus = (data) => {
  switch (data) {
    case 'SUCCESS':
      return '通过'
      break
    case 'FAILURE':
      return '未通过'
      break
    case 'WAIT':
      return '等待'
      break
    case 'LOCK':
      return '禁用'
      break
  }
}

const toHongjian = async (row, flag) => {
  let token = await handleLogin()
  let id = await handleGetProjectId(row)
  if (flag && id) {
    let versions = await handleGetProjectVersion(id)
    let version = versions.find(
      (item) => item.scanVersion == row.commitId.slice(0, 8)
    )?.projectVersion
    if (!version) {
      message.error('本次项目提交，未检测到支持扫描的开发语言，未触发代码检测任务')
      return
    }
    window.open(
      `https://itest-sast.geovisearth.com/projectInfo/${id}/defectList?projectVersion=${version}&&token=${token}`,
      '_blank'
    )
  } else {
    window.open(
      `https://itest-sast.geovisearth.com/projectInfo/${id}/defectList?token=${token}`,
      '_blank'
    )
  }
}

const handleLogin = () => {
  return new Promise(async (resolve) => {
    let params = { userName: 'admin', password: 'fkJpLW1AOTkyaDNzMyFX' }
    const data = await CiApi.login(params)
    let token = data.token
    setHJToken(token)
    resolve(token)
  })
}
const handleGetProjectId = (row) => {
  return new Promise(async (resolve, reject) => {
    let params = { projectName: `${row.projectId}` }
    const data = await CiApi.getProjectIdByName(params)
    if (data) {
      let id = data
      resolve(id)
    } else {
      message.error('项目不存在')
      reject('项目不存在')
    }
  })
}
const handleGetProjectVersion = (id) => {
  return new Promise(async (resolve) => {
    const data = await CiApi.getProjectVersionById({ projectId: id })
    let list = data
    resolve(list)
  })
}

/** 打开弹窗 */
const click = (row?: any, flag?: any) => {
  toHongjian(row, flag)
}

defineExpose({ open, click }) // 提供 open 方法，用于打开弹窗
</script>

<style scoped>
.title {
  padding: 18px 16px 0;
  background-color: rgb(64 158 255 / 10%);
  border-radius: 4px;
}
</style>
